<?php

namespace app\common\model;

/**=========================================
 * Copyright © 2023-2024, WICMS.CN. All Rights Reserved
 * Project Name: WiCMS
 * Description: 后台管理用户模型
 * Author: jason
 * Email: 52527998@QQ.COM
 * Date: 2024/9/18
 * Time: 上午10:45
 * File: app\common\Model\AdminUserModel.php
 * =========================================
 */

use think\Model;
use think\model\relation\BelongsTo;
use think\model\relation\BelongsToMany;

class AdminUserModel extends Model
{

    protected $pk                 = 'id';
    protected $name               = 'AdminUser';
    protected $autoWriteTimestamp = true;
    protected $createTime         = 'create_time';
    protected $updateTime         = 'update_time';

    public function dept(): BelongsTo
    {
        return $this->belongsTo(DepartmentModel::class, 'department_id')->field(['id', 'department_name' => 'name']);
    }

    public function getRoleList(): BelongsToMany
    {
        return $this->belongsToMany(AdminRoleModel::class, AdminRoleAccessModel::class, 'role_id', 'user_id');
    }


    /**
     * 管理员登录
     *
     * @param string $username 用户名
     * @param string $password 登录密码
     *
     * @return array|string
     */
    public static function Login(string $username, string $password): array|string
    {
        $condition = [
            ['username|mobile', '=', $username],
            ['password', '=', md5(sha1($password))]
        ];
        $user      = (new self)->where($condition)->withoutField('password,salt')->findOrEmpty();
        if ($user->isEmpty()) {
            return '用户名或密码错误';
        }
        $result = $user->toArray();
//        $result['roles'] = $user->getRoleList;
        $result['roles']       = ['admin'];
        $result['permissions'] = ['*:*:*'];
        return $result;
    }


}